package com.mdd.maduoduo.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.mdd.maduoduo.MyApplication;
import com.mdd.maduoduo.di.ActivityModule;
import com.mdd.maduoduo.di.component.ApplicationComponent;
import com.mdd.maduoduo.utils.AppManager;

public abstract class BaseActivity extends AppCompatActivity {

    protected Fragment mContent = new Fragment();
    private FragmentManager mFragmentManager;
    private View rootView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getApplicationComponent().inject(this);
        rootView = LayoutInflater.from(this).inflate(getLayoutResId(), null);
        setContentView(rootView);
        AppManager.getAppManager().addActivity(this);
        mFragmentManager = getSupportFragmentManager();
        translucentStatusBar();
        initializeInjector();
        initView();
        onClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
//        ImmersionBar.with(this).destroy();
        AppManager.getAppManager().finishActivity(this.getClass());
        super.onDestroy();
    }

    public void translucentStatusBar() {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }

//    // 切换fragment
//    protected Fragment switchFragment(Fragment to, String tag) {
//        if (mContent != to) {
//            FragmentTransaction transaction = mFragmentManager.beginTransaction();
//            if (!to.isAdded()) { // 先判断是否被add过
//                if (tag.equals("MainFragment")){
//                    transaction.hide(mContent).add(R.id.replace_layout, to, tag).commitAllowingStateLoss(); //
//                }else if (tag.equals("MineFragment")||tag.equals("MessageFragment")||tag.equals("SearchFragment")){
//                    transaction.hide(mContent).add(R.id.replace_mine_layout, to, tag).commitAllowingStateLoss(); //
//                }
//                // 隐藏当前的fragment，add下一个到Activity中
//            } else {
//                transaction.hide(mContent).show(to).commitAllowingStateLoss(); //
//                // 隐藏当前的fragment，显示下一个
//            }
//            mContent = to;
//        }
//        return mContent;
//    }

    protected ApplicationComponent getApplicationComponent() {
        return ((MyApplication) getApplication()).getApplicationComponent();
    }

    /**
     * Get an Activity module for dependency injection.
     */
    protected ActivityModule getActivityModule() {
        return new ActivityModule(this);
    }

    protected abstract int getLayoutResId();

    protected abstract void onClick();

    protected void initView() {

    }

    protected void initializeInjector() {

    }

    private void showToast(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                v.requestFocus();
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
